import asyncio
import json
import os
from fastmcp import FastMCP
from openai import OpenAI
from dashscope import ImageSynthesis

# 创建 FastMCP 服务器
mcp = FastMCP("background-mcp-server")

@mcp.tool()  # 注册为MCP工具 POST
def generate_background_image(
        description: str , 
        negative_describe:str,
        num:int =1, 
        style: str = "realistic", 
        size: str = '1024*1024'
    ) -> str:
    """根据描述生成图片"""
    try:
        # 正向提示词：图片需求
        prompt = f"生成一个 {style} 风格的图片，图片的描述是: {description}"
        # 反向提示词：图片中不包含的元素
        negative_prompt = negative_describe

        response = ImageSynthesis.call(
            api_key=os.getenv("DASHSCOPE_API_KEY","sk-86a0c2d10fde45f5bbf516dcd7102529"),
            model=os.getenv("MODEL_NAME","wanx2.1-t2i-turbo"),
            prompt=prompt,
            negative_prompt=negative_prompt,
            n=num,
            size=size
        )
        
        return f"成功生成图片: {response}"
        
    except Exception as e:
        return f"图片生成失败: {str(e)}"


@mcp.tool()  # 获取资源 类似于GET
def edit_image(url:str , description: str,num:int =1, style: str = "realistic", size: str = '1024*1024') -> str:
    """
    根据描述修改已有的图片
    Args:
        url (str): 图片的URL地址
        description (str): 修改的描述
        num (int): 生成图片数量，默认为1
        style (str): 图片风格，默认为"realistic"
        size (str): 图片尺寸，默认为'1024*1024'
    Returns:
        str: 返回生成的图片信息
    """
    try:
        # 正向提示词：图片需求
        prompt = f"Generate a {style} style background image: {description}"
        # 反向提示词：图片中不包含的元素
        negative_prompt = "红色元素"

        response = ImageSynthesis.call(
            api_key=os.getenv("DASHSCOPE_API_KEY","sk-86a0c2d10fde45f5bbf516dcd7102529"),
            model=os.getenv("MODEL_NAME","wanx2.1-t2i-turbo"),
            prompt=prompt,
            negative_prompt=negative_prompt,
            n=num,
            size=size
        )
        
        return f"成功生成背景图片: {response}"
        
    except Exception as e:
        return f"图片生成失败: {str(e)}"



if __name__ == "__main__":
    # 运行 FastMCP 服务器
    mcp.run(host="localhost", port=8000, transport="streamable-http")